package net.seehope.foodie.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import io.swagger.annotations.Api;
import net.seehope.foodie.common.JsonResult;
import net.seehope.foodie.pojo.Users;
import net.seehope.foodie.pojo.bo.UserBO;
import net.seehope.foodie.pojo.vo.UserInfoVo;
import net.seehope.foodie.pojo.vo.UsernameIsExistVo;
import net.seehope.foodie.service.RegisterService;
import net.seehope.foodie.util.CookieUtils;

@Api("与注册登录有关方法的API")
@RestController
@RequestMapping("/passport")
public class registerController {
	
	@Autowired
	private	HttpServletRequest res;
	@Autowired
	private	HttpServletResponse resp;
	
	@Autowired
	private RegisterService registerService;
	
	@Autowired
	private ObjectMapper objectMapper; 
	
	
	@GetMapping("/usernameIsExist")
	public JsonResult renderusernameIsExist(String username) {	
		registerService.renderusernameIsExist(username);
		return JsonResult.isOk(null);
		
		
	}
	
	
	@PostMapping("/regist")
	public JsonResult regist(@Valid @RequestBody UserBO userBo) throws ParseException {
		registerService.regist(userBo);
		return JsonResult.isOk(null);
		
	}
	
	
	//使用
	@PostMapping("/login")
	public JsonResult login(@Valid @RequestBody UserBO userBO) throws JsonProcessingException, UnsupportedEncodingException {
	//TODO 目前在单体架构中，使用cookie去维护登录状态，在之后服务演进的过程中，存储逻辑会去修改	
	
		/**
		 * 自动判断request的域名并设置domain，同时设置path为/ 也就是request域名下
		 * 所有网址，该cookie都有效
		 * 604800 有效期
		 * true是否编码，cookie当成json传到前端的时候需要编码，因为不能有空格，双引号之类的字符串，所以要URLENCODE
		 * 
		 */
		CookieUtils.setCookie(res, resp, "user", objectMapper.writeValueAsString(registerService.login(userBO)), 604800, true);
		
		return JsonResult.isOk(null);
	}
	
	
	@GetMapping("/me")
	public Authentication showToken(Authentication token) {
		return token;
	}
	
	

}
